/**
 * ===========================================
 * Project: cyou-framework
 * ===========================================
 * Package: com.cyou.framework.exception
 * 
 * Copyright (c) 2012, CYOU All Rights Reserved.
 * ===========================================
 */
package com.cyou.framework.exception;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * <p>ExceptionUtility</p>
 * <p>
 * Description:
 * 关于异常的工具类. 提供如下方法：
 * </p>
 * <p>
 * 1. unchecked - 将CheckedException转换为UncheckedException. <br>
 * 2. getStackTraceAsString - 将ErrorStack转化为String. <br>
 * 3. isCausedBy - 判断异常是否由某些底层的异常引起.
 * </p>
 *
 * @since 1.0
 * @version 1.0 2012-11-30
 * @author zhangxingkai
 */
public class ExceptionUtility {

	/**
	 * 将CheckedException转换为UncheckedException.
	 */
	public static RuntimeException unchecked(Exception e) {
		if (e instanceof RuntimeException) {
			return (RuntimeException) e;
		} else {
			return new RuntimeException(e);
		}
	}

	/**
	 * 将ErrorStack转化为String.
	 */
	public static String getStackTraceAsString(Exception e) {
		StringWriter stringWriter = new StringWriter();
		e.printStackTrace(new PrintWriter(stringWriter));
		return stringWriter.toString();
	}

	/**
	 * 判断异常是否由某些底层的异常引起.
	 */
	public static boolean isCausedBy(Exception ex, Class<? extends Exception>... causeExceptionClasses) {
		Throwable cause = ex.getCause();
		while (cause != null) {
			for (Class<? extends Exception> causeClass : causeExceptionClasses) {
				if (causeClass.isInstance(cause)) {
					return true;
				}
			}
			cause = cause.getCause();
		}
		return false;
	}
}
